var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphone_x: false,
    screen_w: 320,
    screen_h: 480,
    msgScrollView_h: 250,

    userInfo: '',
    cuid: '',

    toUserInfo: '',
    toUid: '',
    massageList: '',

    inputContent: '',

    scrollTop: 0,

    showVideo: false
  },

  token: '',

  sayHello: false,

  giveMsgCount: 0,
  giveMsgTitle: '',
  giveMsgToast: '',
  hasMsgCount: 0,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    this.sayHello = options.sayhello ? true : false
    
    var that = this

    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
    })

    app.getUserInfo(options.uid, function(res){
      that.setData({
        toUserInfo: res
      })
      tt.setNavigationBarTitle({
        title: res.uname ? res.uname : '匿名的Ta',
      })
    })
    app.LoginUserInfo(function (res) {
      if (res != '-1' && res != '-2') {
        that.setData({
          cuid: res.uid,
          userInfo: res,
          toUid: options.uid
        })
        that.token = res.token
        that.getMessages()
        that.hasMsgCount = parseInt(res.scorecoin) - parseInt(res.scorenum)
        that.getGiveMsgInfo()
      }
    })
  },

  getMessages() {
    //     get请求http://admin.jawanology.com/go.php?ac=getmsgcontent&uid=1&touid=2&publickey=ZGZvI1mi8Q
    // 传入ac=getmsgcontent-接口标识，uid-发送者uid，touid-接收者uid
    // 返回聊天内容，包括 uid-发送者uid，touid-接收者uid，send_time-发送时间，content-聊天内容。根据这里的uid和touid哪个和传入的uid和touid相等来判断是谁发给谁的。
    // 调用这个接口后，会清空列表接口中touid等于uid的未读消息数量。

    var that = this
    util.api_go({
      data: {
        "publickey": util.publiccode,
        "ac": "getmsgcontent",
        "uid": that.data.cuid,
        "touid": that.data.toUid
      },
      success: function (responseData) {
        console.log("信息列表：", responseData);
        if (responseData.data) {
          if (!responseData.msg && responseData.data.length > 0) {
            let msgArr = []
            let len = responseData.data.length
            let newlistMsgId = responseData.data[0].id
            let oldMsgLen = that.data.massageList.length
            let oldMsgId = oldMsgLen > 0 ? that.data.massageList[oldMsgLen - 1].id : ''
            if (len != oldMsgLen || newlistMsgId != oldMsgId) {
              let sendTimeStr = ''
              for (let i = len - 1; i >= 0; i--) {
                let itemData = responseData.data[i]
                if (i == len - 1) {
                  sendTimeStr = itemData.send_time
                  itemData.showTime = that.dealTime(sendTimeStr, '')
                } else {
                  itemData.showTime = that.dealTime(sendTimeStr, itemData.send_time)
                  if (itemData.showTime && itemData.showTime.length > 0) {
                    sendTimeStr = itemData.send_time
                  }
                }
                itemData.decodeMsg = base64.decode(itemData.content)
                msgArr.push(itemData)
              }
              console.log("显示列表：", msgArr);
              that.setData({
                massageList: msgArr,
                scrollTop: len * 300,
                inputContent: that.messageStr
              })
            }
            if(that.sayHello){
              that.messageStr = that.sayHello ? 'Hi,你好' : that.messageStr
              that.sayHello = false
              that.setData({
                inputContent: that.messageStr
              })
            }
          } else {
            that.setData({
              massageList: []
            })
            if(that.sayHello){
              that.sayHello = false
              that.sendMessage("Hi,你好")
            }
          }
        } else {
          tt.showToast({
            title: '获取信息失败',
          })
        }
      }
    });
  },

  dealTime(timeStr1, timeStr2){
    let showTimeStr = ""
    if(!timeStr2 || timeStr2.length <= 0) {
      showTimeStr = timeStr1.slice(0, timeStr1.length - 3)
    } else {
      new Date()
      let allTimeArr1 = timeStr1.split(' ')
      let dayArr1 = allTimeArr1[0].split('-')
      let timeArr1 = allTimeArr1[1].split(':')
      let year1 = dayArr1[0]
      let mon1 = dayArr1[1]
      let day1 = dayArr1[2]
      let hour1 = timeArr1[0]
      let minute1 = parseInt(timeArr1[1])

      let allTimeArr2 = timeStr2.split(' ')
      let dayArr2 = allTimeArr2[0].split('-')
      let timeArr2 = allTimeArr2[1].split(':')
      let year2 = dayArr2[0]
      let mon2 = dayArr2[1]
      let day2 = dayArr2[2]
      let hour2 = timeArr2[0]
      let minute2 = parseInt(timeArr2[1])

      if (year1 != year2) {
        showTimeStr = allTimeArr2[0] + ' ' + allTimeArr2[1].slice(0, allTimeArr2[1].length - 3)
      } else if (mon1 != mon2 || day1 != day2) {
        showTimeStr = mon2 + '-' + day2 + ' ' + allTimeArr2[1].slice(0, allTimeArr2[1].length - 3)
      } else if (hour1 != hour2 || minute2 - minute1 >= 3) {
        showTimeStr = allTimeArr2[1].slice(0, allTimeArr2[1].length - 3)
      }
    }
    return showTimeStr
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  requestTimer: '',

  startTimerRequest() {
    var that = this
    if (this.requestTimer) {
      console.log("清除定时器")
      clearInterval(this.requestTimer)
    }
    console.log("开启定时器")
    that.requestTimer = setInterval (
      function () {
        that.getMessages()
      }
    , 8000)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    app.initScreenInfo(function (res) {
      if (res) {
        that.setData({
          isIphone_x: app.isIphone_x,
          screen_w: app.screen_w,
          screen_h: app.screen_h,
          msgScrollView_h: app.screen_h - (app.isIphone_x ? 90 : 70)
        });
      }
    })
    this.startTimerRequest()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("chatMessage onHide!!!!!! 清除定时器")
    clearInterval(this.requestTimer)
    this.requestTimer = ''
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("chatMessage onUnload!!!!!! ")
    if (this.requestTimer) {
      console.log("清除定时器")
      clearInterval(this.requestTimer)
    }
    this.requestTimer = ''
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  messageStr: "",
  inputAction(e) {
    this.messageStr = e.detail.value
    var that  = this
    this.setData({
      inputContent: that.messageStr
    })
  },

  sendMessageBtnAction (e) {
    let noGetSubMsg = app.noSubscribeMessageCache()
    console.log("已经授权订阅消息：" + noGetSubMsg)
    if (noGetSubMsg) {
      tt.requestSubscribeMessage({
        tmplIds: [app.globalData.tmplMsgIds],
        success(res) {
          console.log("订阅消息结果：", res)
          if (res.errMsg.indexOf(":ok") > 0) {
            app.setSubscribeMessageCache()
          }
        }
      })
    }
    this.sendMessage(this.messageStr)
  },

  sendMessage: function (message) {
    // post请求，ac=postmsg，传入uid-发送者uid，touid-接收者uid，msg-消息内容。返回操作成功/失败。调用成功后 会增加消息列表接口中的未读数量
    if(!message || message.length <= 0) {
      tt.showToast({
        title: '请输入内容',
      })
      return;
    }
    let message64 = base64.encode(message)
    var that = this;
    let privateKey = utilMd5.hexMD5(app.globalData.cuid + "postmsg" + app.globalData.token);
    let commitData = {
      "privatekey": privateKey,
      "ac": "postmsg",
      "uid": app.globalData.cuid,
      "touid": that.data.toUid,
      "msg": message64
    };
    console.log("发送消息：", commitData)
    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log("发送消息返回：", responseData);
        if (responseData.data.res) {
          that.setData({
            inputContent: ''
          })
          that.messageStr = ""
          that.getMessages()
        } else {
          that.showNoMessageCountModal(responseData.data.msg)
        }
      }
    });
  },

  showNoMessageCountModal: function (msg) {
    let userTag = this.data.userInfo.tag
    let day = new Date().getDate()
    let isGiveToday = tt.getStorageSync('givemsg')
    console.log("每天赠送:" + day + ", isGiveToday = " + isGiveToday + ", hasMsgCount = " + this.hasMsgCount);
    if(this.giveMsgCount > 0 && this.giveMsgCount > this.hasMsgCount && isGiveToday != day) {
      this.giveMessage()
    } else if (!app.userInfoIsComplete(userTag)) {
      tt.showModal({
        title: '温馨提示',
        content: "可用信息条数不足，充值或完善个人资料可获得免费信息条数",
        confirmText: "充值",
        cancelText: "完善资料",
        success (res) {
          if (res.confirm) {
            tt.navigateTo({
              url: '/pages/chongzhi/chongzhi'
            })    
          } else {
            tt.navigateTo({
              url: '/pages/mineInfoEdit/mineInfoEdit'
            })
          }
        }
      })
    } else {
      tt.showModal({
        title: '温馨提示',
        content: msg,
        confirmText: "充值",
        success (res) {
          if (res.confirm) {
            tt.navigateTo({
              url: '/pages/chongzhi/chongzhi'
            })    
          }
        }
      })
    }
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },

  //index 005  获取每日赠送信息
  getGiveMsgInfo: function () {
    var that = this
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": '5'
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log("每天赠送信息:", responseData);
        if(responseData.data && !responseData.data.msg){
          var result = responseData.data;
          try {
            that.giveMsgCount = parseInt(result[0].title)
          } catch (err) { 
            that.giveMsgCount = 0
          }
          console.log("赠送条数:" + that.giveMsgCount)
          that.giveMsgTitle = result[0].navtitle
          that.giveMsgToast = result[0].data
          let day = new Date().getDate()
          if (that.giveMsgCount < that.hasMsgCount) {
            //当天剩余信息条数大于等于赠送条数时，当天不再赠送。
            tt.setStorage({
              key: "givemsg",
              data: day
            })
          }
        }
      }
    });
  },

  giveMessage: function() {
      var that = this
      app.addMessageCount(that.giveMsgCount, function(respon) {
        if (respon.res) {
          let day = new Date().getDate()
          tt.setStorage({
            key: "givemsg",
            data: day
          })
          tt.showModal({
            title: that.giveMsgTitle,
            content: that.giveMsgToast,
            showCancel: false,
            success (res) {
              if (res.confirm) {
                that.sendMessage(that.messageStr)
              }
            }
          })
        }
      })
  },

  sendImage () {
    tt.showToast({
      title: '您暂未有权限',
    })
  }

})